import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:video_player/video_player.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  // 添加静态变量来存储视频控制器
  static VideoPlayerController? videoController;
  
  // 添加静态方法来控制视频
  static void setVideoController(VideoPlayerController controller) {
    videoController = controller;
  }
  
  static void pauseVideo() {
    if (videoController != null && videoController!.value.isPlaying) {
      videoController!.pause();
    }
  }
  
  static void resumeVideo() {
    if (videoController != null && !videoController!.value.isPlaying) {
      videoController!.play();
    }
  }

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  void initState() {
    super.initState();
    WidgetsFlutterBinding.ensureInitialized().addPostFrameCallback((_) {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (_) {
            return ConstrainedBox(
              constraints: BoxConstraints(
                maxWidth: 200,
                maxHeight: 100,
              ),
              child: const ToChatDialog(),
            );
          });
    });
  }

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      backgroundColor: Colors.white,
    );
  }
}

class ToChatDialog extends Dialog {
  const ToChatDialog({super.key});

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      contentPadding: EdgeInsets.zero,
      buttonPadding: EdgeInsets.zero,
      titlePadding: EdgeInsets.all(5),
      title: const Text(
        "兑换码",
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 18),
      ),
      insetPadding: EdgeInsets.zero,
      actionsAlignment: MainAxisAlignment.spaceAround,
      actionsPadding: EdgeInsets.only(bottom: 15),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text("请获取兑换码并输入", style: TextStyle(fontSize: 12)),
          Container(
            width: 180,
            height: 40,
            child: TextField(
              style: TextStyle(fontSize: 12, color: Colors.grey),
              decoration: InputDecoration(
                contentPadding: EdgeInsets.symmetric(horizontal: 10),
              ),
            ),
          ),
          SizedBox(
            height: 10,
          )
        ],
      ),
      actions: [
        SizedBox(
          width: 90,
          child: TextButton(
            onPressed: () {
              // 进入WebView前暂停视频
              HomePage.pauseVideo();
              Navigator.push(
                context,
                PageRouteBuilder(
                  pageBuilder: (context, animation, secondaryAnimation) => const WebViewPage(),
                  transitionsBuilder: (context, animation, secondaryAnimation, child) {
                    return FadeTransition(
                      opacity: animation,
                      child: child,
                    );
                  },
                  transitionDuration: const Duration(milliseconds: 200),
                ),
              );
            },
            child: Text(
              "获取验证码",
              style: TextStyle(fontSize: 12, color: Colors.blueAccent),
            ),
            style: TextButton.styleFrom(
                side: BorderSide(color: Colors.blueAccent, width: 1.0)),
          ),
        ),
        SizedBox(
          width: 90,
          child: TextButton(
            onPressed: () {},
            child: Text(
              "验证",
              style: TextStyle(fontSize: 12, color: Colors.white),
            ),
            style: TextButton.styleFrom(backgroundColor: Colors.blueAccent),
          ),
        ),
      ],
    );
  }
}

class WebViewPage extends StatefulWidget {
  const WebViewPage({super.key});

  @override
  State<WebViewPage> createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  late final WebViewController controller;
  bool isLoading = true;
  bool hasError = false;
  String errorMessage = '';

  @override
  void initState() {
    super.initState();
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(Colors.white)
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageStarted: (String url) {
            setState(() {
              isLoading = true;
            });
          },
          onPageFinished: (String url) {
            setState(() {
              isLoading = false;
            });
          },
          onWebResourceError: (WebResourceError error) {
            setState(() {
              isLoading = false;
              hasError = true;
              errorMessage = '加载失败: ${error.description}';
            });
          },
        ),
      );
    
    controller.loadRequest(Uri.parse('http://tiktck.dezhen5.top/tk.html'));
  }

  @override
  void dispose() {
    // 页面关闭时恢复视频播放
    HomePage.resumeVideo();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.white,
        child: Stack(
          children: [
            WebViewWidget(controller: controller),
            if (isLoading)
              AnimatedOpacity(
                opacity: isLoading ? 1.0 : 0.0,
                duration: const Duration(milliseconds: 150),
                child: Container(
                  color: Colors.white,
                  child: const Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        CircularProgressIndicator(
                          valueColor: AlwaysStoppedAnimation<Color>(Colors.blueAccent),
                        ),
                        SizedBox(height: 16),
                        Text('正在加载网页...', style: TextStyle(color: Colors.grey)),
                      ],
                    ),
                  ),
                ),
              ),
            if (hasError)
              AnimatedOpacity(
                opacity: hasError ? 1.0 : 0.0,
                duration: const Duration(milliseconds: 150),
                child: Container(
                  color: Colors.white,
                  child: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.error_outline, size: 64, color: Colors.red),
                        SizedBox(height: 16),
                        Text(errorMessage, style: TextStyle(color: Colors.red)),
                        SizedBox(height: 16),
                        ElevatedButton(
                          onPressed: () {
                            setState(() {
                              hasError = false;
                              isLoading = true;
                            });
                            controller.reload();
                          },
                          child: Text('重试'),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
}
